package parser

import (
	"aqielife.cn/spider/models"
	"aqielife.cn/spider/utils"
	"bufio"
	"github.com/PuerkitoBio/goquery"
	"golang.org/x/text/transform"
	"log"
	"math/rand"
	"net/http"
	"strings"
	"time"
)

type ArticleAnalyzer interface {
	AnalyzeList(httpRes *http.Response) []models.ArticleDetail
	AnalyzeDetail(httpRes *http.Response, shares models.ArticleDetail) *models.ArticleDetail
}

type XinhuaAnalyzer struct {
	ArticleAnalyzer
}

func NewXinhuaAnalyzer() ArticleAnalyzer {
	return &XinhuaAnalyzer{}
}

func (a *XinhuaAnalyzer) AnalyzeList(httpRes *http.Response) []models.ArticleDetail {
	if httpRes.StatusCode != 200 {
		log.Println("请求失败", httpRes.StatusCode)
	} else {
		log.Println(httpRes.StatusCode)
	}
	bodyReader := bufio.NewReader(httpRes.Body) // 包装下
	rand.Seed(time.Now().UnixNano())

	e := utils.DetermineEncoding(bodyReader)
	utf8Reader := transform.NewReader(bodyReader, e.NewDecoder())
	doc, _ := goquery.NewDocumentFromReader(utf8Reader)

	var pages []models.ArticleDetail
	doc.Find("div#focusListNews > ul > li").Each(func(i int, s *goquery.Selection) {
		url, _ := s.Find("span > a").Attr("href")
		id := utils.GenID()
		pages = append(pages, models.ArticleDetail{
			ID:  id,
			Url: url,
		})
	})
	return pages
}

func (a *XinhuaAnalyzer) AnalyzeDetail(httpRes *http.Response, detail models.ArticleDetail) *models.ArticleDetail {
	if httpRes.StatusCode != 200 {
		log.Println("请求失败", httpRes.StatusCode)
	}
	// body -> doc
	bodyReader := bufio.NewReader(httpRes.Body) // 包装下
	e := utils.DetermineEncoding(bodyReader)
	utf8Reader := transform.NewReader(bodyReader, e.NewDecoder())
	doc, _ := goquery.NewDocumentFromReader(utf8Reader)

	var images []string
	title := doc.Find("div.header.domPC span.title").Text()
	if title == "" {
		title = doc.Find("div.xl-cont-head h1").Text()
	}
	content := doc.Find("div#detail > p").Text()

	doc.Find("div#detail > p").Each(func(i int, s *goquery.Selection) {
		img, _ := s.Find("img").Attr("src")
		if img != "" {
			images = append(images, img)
		}
	})
	content = strings.TrimSpace(content)
	if content == "" || strings.TrimSpace(title) == "" {
		return nil
	}

	return &models.ArticleDetail{
		ID:      detail.ID,
		Url:     detail.Url,
		Title:   title,
		Content: utils.DeleteExtraSpace(content),
		Type:    utils.NEWS,
		Images:  strings.Join(images, ","),
		Status:  0,
	}

}
